package com.thwcompany.rabbitMQ.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@SuppressWarnings("all")
public class DirectListener1 {
	//发布-订阅模式，这里配置消费者1号监听消息队列directqueue1
	//@RabbitListener(queues = "directqueue1")
	//public void displayMail(Mail mail, Channel channel, Message message) throws Exception {
	//	System.out.println("direct消费者1号，从directqueue1消息队列监听到的消息是："+mail.toString());
	//
	//	//消费者1号进行手工确认签收消息
	//	long deliveryTag = message.getMessageProperties().getDeliveryTag();
	//	System.out.println("消费者1号签收消息，deliveryTag："+deliveryTag);
	//	try {
	//		channel.basicAck(deliveryTag,false);
    //        System.out.println("消费者1号签收消息成功");
	//	} catch (Exception e) {
	//		//签收失败的消息重新压入MQ
	//		channel.basicRecover();
	//		e.printStackTrace();
	//	}
	//}


	@RabbitListener(queues = "directqueue1")
	public void displayMail(Channel channel, Message message) throws Exception {
		//System.out.println("direct消费者1号，从directqueue1消息队列监听到的消息是："+mail.toString());
		System.out.println("direct消费者1号，从directqueue1消息队列监听到的消息是："+new String(message.getBody(), StandardCharsets.UTF_8));

		//消费者1号进行手工确认签收消息
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		System.out.println("消费者1号签收消息，deliveryTag："+deliveryTag);
		try {
			channel.basicAck(deliveryTag,false);
			System.out.println("消费者1号签收消息成功");
		} catch (Exception e) {
			// 处理消息处理失败的情况
			//channel.basicRecover();
			channel.basicNack(deliveryTag, false, true);
			e.printStackTrace();
		}
	}

}
